package cn.sky.demo.config;


import cn.sky.demo.annotation.limit.RequestLimit;
import cn.sky.demo.hander.interceptor.LoginInterceptor;
import cn.sky.demo.hander.interceptor.RequestLimitInterceptor;
import cn.sky.demo.hander.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    private static final String[] excludePathPatterns  = {"/api/token/api_token"};

    @Autowired
    private LoginInterceptor loginInterceptor;
    @Autowired
    private TokenInterceptor tokenInterceptor;
    @Autowired
    private RequestLimitInterceptor requestLimitInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestLimitInterceptor);
                //.addPathPatterns("/limit/**");
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/web/**")
                .addPathPatterns("/admin/**")
                .addPathPatterns("/test1/**");
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns(excludePathPatterns);
    }
    /**
     * 跨域配置
     * 1、SpringBoot 配置 CORS 解决跨域
     * 在项目中创建一个新的配置文件
     * 添加@Configuration注解实现WebMvcConfigurer接口
     * 重写addCorsMappings方法并设置允许跨域的代码
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*") // 支持域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}
